package com.suishoupai.xmb.controller;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.druid.util.StringUtils;
import com.suishoupai.xmb.entity.AjaxMessage;
import com.suishoupai.xmb.entity.RoleEnum;
import com.suishoupai.xmb.exception.XmbException;
import com.suishoupai.xmb.service.BaiduMapService;
import com.suishoupai.xmb.service.UserService;
import com.suishoupai.xmb.service.ImageService;
import com.suishoupai.xmb.service.VerificationCodeService;
import com.suishoupai.xmb.utils.SecurityUserUtil;
import com.suishoupai.xmb.utils.ValidateUtil;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * Created by caojian on 2017/3/17.
 */
@Controller
public class DefaultController {
    private static final Log LOG = LogFactory.getLog(DefaultController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private BaiduMapService baiduMapService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private VerificationCodeService verificationCodeService;
    @Autowired
    private ImageService imageService;

    /**
     * 登录页面
     *
     * @param message
     * @param model
     * @return
     */
    @GetMapping("/login")
    @PreAuthorize("permitAll()")
    public String loginPage(@ModelAttribute("message") String message, Model model) {
        model.addAttribute("message", message);
        return "login";
    }

    /**
     * 获取图文验证码
     *
     * @return
     */
    @GetMapping("/code")
    @PreAuthorize("permitAll()")
    public void code(HttpServletResponse response, HttpSession session) {
        try {
            verificationCodeService.fillImageCode(response, session);
        } catch (XmbException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/login")
    @PreAuthorize("permitAll()")
    @ResponseBody
    public Object login(@RequestParam Map map) {
        String username = MapUtils.getString(map, "username", null);
        String password = MapUtils.getString(map, "password", null);
        String verificationCode = MapUtils.getString(map, "verificationCode", null);
        ValidateUtil.notNull(username);
        ValidateUtil.notNull(password);
        try {
            Long userId = userService.login(username, password, verificationCode);
            return AjaxMessage.newSuccessMsg(userId);
        } catch (XmbException e) {
            if (e.isVerification()) {
                return AjaxMessage.newErrorVerificationMsg(e.getError());
            }
            return AjaxMessage.newErrorHintMsg(e.getError());
        }
    }

    /**
     * 登录成功后的跳转
     *
     * @return
     */
    @RequestMapping("/loginSuccess")
    @PreAuthorize("isAuthenticated()")
    public ModelAndView loginSuccess() {
        List<RoleEnum> roles = SecurityUserUtil.getRoles();
        for (RoleEnum role : roles) {
            if (role.getValue().equals(RoleEnum.ADMIN.getValue())) {
                return new ModelAndView(new RedirectView("/sale", true, false, true));
            } else if (role.getValue().equals(RoleEnum.USER.getValue())) {
                throw new RuntimeException("买家不应该进这里。");
            } else if (role.getValue().equals(RoleEnum.SALE.getValue())) {
                return new ModelAndView(new RedirectView("/sale/orders", true, false, true));
            }
        }
        throw new RuntimeException("不认识的账号");
    }

    /**
     * 对首页请求作内部跳转
     *
     * @return
     */
    @GetMapping("")
    @PreAuthorize("isAuthenticated()")
    public String index() {
        return "forward:/loginSuccess";
    }

    @GetMapping("/introduction")
    @PreAuthorize("permitAll()")
    public Object introduction() {
        return "introduction";
    }

    @GetMapping("/location")
    @PreAuthorize("isAuthenticated()")
    public Object locationChoice(String callback, Model model) {
        model.addAttribute("ak", baiduMapService.getAk());
        model.addAttribute("callback", callback);
        return "location-choice";
    }

    @GetMapping("/image")
    @PreAuthorize("permitAll()")
    public void image(String key, HttpServletResponse response) {
        if (StringUtils.isEmpty(key)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        try {
            imageService.fillImage8qiniukey(key);
        } catch (XmbException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
